import subprocess
import sys
import time
import yum

class ConfigurePackages:
    def __init__(self, packages):
        self.packages = packages
        self.successful = 0
        self.failed     = 0
        self.oo_sync    = 0

    def configure(self):
        print "\033[1;36m- Configuring Packages\033[1;m"
        runtime_start = time.time()

        # Setup YumBase
        yb = yum.YumBase()
        # Run in quite mode
        yb.preconf.debuglevel = 0
        yb.preconf.errorlevel = 0
        yb.doTsSetup()
        yb.doRpmDBSetup()

        # Setup YumCLI
        sys.path.append('/usr/share/yum-cli')
        import cli

        ybc = cli.YumBaseCli()
        # Run in quite mode
        ybc.preconf.debuglevel = 0
        ybc.preconf.errorlevel = 0
        # Assume yes to prevent Yum from prompting [Y/N]
        ybc.conf.assumeyes = True
        ybc.doTsSetup()
        ybc.doRpmDBSetup()

        pkg_list = list([package for package in self.packages])

        for package in self.packages:
            if yb.isPackageInstalled(package):
                pkg_list.remove(package)
                self.successful += 1

        if pkg_list:
            print "  Packages out of sync: %s" % pkg_list
            ybc.installPkgs(pkg_list)
            ybc.buildTransaction()
            #ybc.conf.setConfigOption('assumeyes',True)
            ybc.doTransaction()

            self.oo_sync += len(pkg_list)

        # Collect Stats
        runtime_end = time.time()
        runtime = (runtime_end - runtime_start)

        stats = {
            'runtime'   : runtime,
            'successful': self.successful,
            'failed'    : self.failed,
            'oo_sync'   : self.oo_sync
        }

        return stats
